package com.zrx.app.android.modules;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.zrx.app.android.R;
import com.zrx.app.android.UTIL.RemoteConn;
import com.zrx.app.android.activity.ContentActivity;
import com.zrx.app.android.service.UploadService;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**
 * Created by liuji on 2017/5/25.
 *
 * 车商收据录入页面
 */

public class LoanReceiptActivity extends BaseModuleActivity{

    private static final String TAG = "LoanReceiptActivity";

    public static void startActivity(Context context, JSONObject record) {
        Intent intent = new Intent(context,LoanReceiptActivity.class);
        intent.putExtra("record",record.toJSONString());
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.activity_template);
        super.onCreate(savedInstanceState);

        label_module_name.setText("车商收据录入");
        JSONObject rawRecord = savedJson.getJSONObject("rawRecord");
        String state = rawRecord.getString("state");

        LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if ("LOAN_PAYMENT_OUT_CONFIRM_PASS".equals(state) || "LOAN_RECEIPT_CONFIRM_SENDBACK".equals(state)) {
            Button btn = (Button) inflater.inflate(R.layout.button, catalog, false);
            btn.setText("提交");
            btn.setEnabled(true);
            final BaseModuleActivity thisAct = this;
            final JSONObject root = savedJson;
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(thisAct);
                    if (!RemoteConn.getInstance().isAuthed()) {
                        builder.setMessage("请先登录！");
                        builder.setTitle("请先登录");
                        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                thisAct.finish();
                            }
                        });
                    } else {
                        builder.setMessage("确认提交吗？");
                        builder.setTitle("确认");
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();

                                String email = RemoteConn.getInstance().getEmail();
                                String password = RemoteConn.getInstance().getPassword();
                                root.put("email", email);
                                root.put("password", password);

                                root.put("state", "车商收据提交");
                                root.put("editable", false);
                                save(root, rootPath + "/obj.json", true);

                                Intent i = new Intent(v.getContext(), UploadService.class);
                                JSONObject req = new JSONObject();
                                req.put("taskName", "车商收据提交");
                                req.put("id", root.getJSONObject("rawRecord").getString("id"));
                                i.putExtra("taskJson", req.toJSONString());
                                startService(i);
                                thisAct.finish();
                            }
                        });

                    }
                    builder.create().show();
                }
            });
            catalog.addView(btn);
        }

    }

    @Override
    protected String getModuleName(){
        return "车商收据";
    }

    JSONObject getTemplate(){
        InputStream res = getResources().openRawResource(R.raw.loan_receipt_template);

        Scanner sc = new Scanner(res);
        StringBuffer sb = new StringBuffer();
        while (sc.hasNextLine())
            sb.append(sc.nextLine());
        sc.close();
        return JSON.parseObject(sb.toString(), Feature.OrderedField);
    }

    @Override
    void fillData(JSONObject data) {
        JSONObject rawRecord = savedJson.getJSONObject("rawRecord");
        JSONObject loanReceiptRecord = savedJson.getJSONObject("loanReceiptRecord");
        String id = rawRecord.getString("id");
        loanReceiptRecord.put("id", id);

        String rawState = "";
        if (rawRecord != null && rawRecord.containsKey("state"))
            rawState = rawRecord.getString("state");
        String recordState = "";
        if (savedJson.containsKey("state"))
            recordState = savedJson.getString("state");

        if ("LOAN_RECEIPT_CONFIRM_SENDBACK".equals(rawState) && "车商收据提交".equals(recordState) && "完成".equals(savedJson.get("loanReceiptState"))) {
            savedJson.put("editable", true);
            savedJson.remove("state");
        }

        Map<String, Object> allTarNode = new HashMap<>();
        for (String key : loanReceiptRecord.keySet()) {
            Object _ele = loanReceiptRecord.get(key);
            if (_ele != null && _ele instanceof JSONObject) {
                JSONObject l2 = (JSONObject) _ele;
                Set<String> l2KeySet = l2.keySet();
                for (String l2Key : l2KeySet) {
                    Object obj = l2.get(l2Key);
                    if (obj != null && obj instanceof JSONObject)
                        allTarNode.put(l2Key, obj);
                }
            }
        }

        Map<String, Object> allSrcNode = new HashMap<>();
        if(rawRecord.containsKey("loanInfo")&&rawRecord.getJSONObject("loanInfo").containsKey("loan_pics"))
            allSrcNode.putAll(rawRecord.getJSONObject("loanInfo").getJSONObject("loan_pics"));

        if (allSrcNode != null)
            for (String srcKey : allSrcNode.keySet()) {
                try {
                    String srcVal = (String) allSrcNode.get(srcKey);
                    boolean flag = false;
                    boolean editable = true;

                    for (String tarKey : allTarNode.keySet()) {
                        JSONObject tar = (JSONObject) allTarNode.get(tarKey);
                        boolean appendable = false;
                        if (tar.containsKey("appendable")) {
                            appendable = tar.getBoolean("appendable");
                        }

                        if (tar.containsKey("editable")) {
                            editable = tar.getBoolean("editable");
                        }

                        if (srcKey != null && tarKey != null && appendable && srcKey.contains(tarKey)) {
                            JSONObject innerNode = tar.getJSONObject("val");
                            if (innerNode == null) {
                                innerNode = new JSONObject();
                                tar.put("val", innerNode);
                            }
                            //innerNode.put(srcKey,val);
                            JSONObject _tar = null;
                            if (innerNode.containsKey(srcKey))
                                _tar = innerNode.getJSONObject(srcKey);
                            else {
                                _tar = new JSONObject();
                                innerNode.put(srcKey, _tar);
                            }
                            _tar.put("type", tar.getString("type"));

                            updateEle(_tar, srcKey, srcVal, id, editable);
                            flag = true;
                        }else if (tarKey != null && tarKey.equals(srcKey)) {
                            updateEle(tar, srcKey, srcVal, id, editable);
                            flag = true;
                        }  else if (tar.containsKey("alias")) {
                            JSONArray arrKey = tar.getJSONArray("alias");
                            for (Object aliasKey : arrKey) {
                                if (aliasKey != null && aliasKey.equals(srcKey)) {
                                    updateEle(tar, srcKey, srcVal, id, editable);
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if (flag)
                            break;
                    }

                } catch (Exception e) {
                    Log.d(TAG, e.getMessage());
                }

            }
    }

    @Override
    String getModuleKey() {
        return "loanReceiptRecord";
    }
}
